package cn.iocoder.yudao.module.call.controller.admin.vosnumber;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.ip.core.enums.AreaTypeEnum;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.module.call.controller.admin.vosnumber.vo.VosNumberPageReqVO;
import cn.iocoder.yudao.module.call.controller.admin.vosnumber.vo.VosNumberRespVO;
import cn.iocoder.yudao.module.call.controller.admin.vosnumber.vo.VosNumberRespWithCountVO;
import cn.iocoder.yudao.module.call.controller.admin.vosnumber.vo.VosNumberSaveReqVO;
import cn.iocoder.yudao.module.call.convert.location.VosNumberConverter;
import cn.iocoder.yudao.module.call.dal.dataobject.location.LocationDO;
import cn.iocoder.yudao.module.call.dal.dataobject.vosnumber.VosNumberDO;
import cn.iocoder.yudao.module.call.dal.dataobject.whiteaudit.WhiteAuditDO;
import cn.iocoder.yudao.module.call.service.location.LocationService;
import cn.iocoder.yudao.module.call.service.vosnumber.VosNumberService;
import cn.iocoder.yudao.module.system.api.tenant.TenantApi;
import cn.iocoder.yudao.module.system.api.tenant.dto.TenantDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 号码")
@RestController
@RequestMapping("/call/vos-number")
@Validated
public class VosNumberController {

    @Resource
    private VosNumberService vosNumberService;

    @Resource
    private TenantApi tenantApi;

    @PostMapping("/create")
    @Operation(summary = "创建号码")
    @PreAuthorize("@ss.hasPermission('call:location:create')")
    public CommonResult<Long> createVosNumber(@Valid @RequestBody VosNumberSaveReqVO createReqVO) {
        return success(vosNumberService.createVosNumber(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新号码")
    @PreAuthorize("@ss.hasPermission('call:location:update')")
    public CommonResult<Boolean> updateVosNumber(@Valid @RequestBody VosNumberSaveReqVO updateReqVO) {
        vosNumberService.updateVosNumber(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除号码")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('call:location:delete')")
    public CommonResult<Boolean> deleteVosNumber(@RequestParam("id") Long id) {
        vosNumberService.deleteVosNumber(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得号码")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<VosNumberRespVO> getVosNumber(@RequestParam("id") Long id) {
        VosNumberDO numberPool = vosNumberService.getVosNumber(id);
        return success(BeanUtils.toBean(numberPool, VosNumberRespVO.class));
    }

    @GetMapping("/get-number-count")
    @Operation(summary = "获得各地区的号码数量")
    public CommonResult<Map<Long, Integer>> getVosNumberCount() {
        List<Map<String, Long>> list = vosNumberService.getVosNumberCount();
        Map<Long, Integer> result = new HashMap<>();
        for (Map<String, Long> data : list
        ) {
            result.put(data.get("name"), data.get("value").intValue());
            // 找parentId
            Integer parentId = AreaUtils.getParentIdByType(data.get("name").intValue(), AreaTypeEnum.PROVINCE);
            if (Objects.nonNull(parentId)) {
                if (result.containsKey(parentId.longValue())) {
                    result.put(parentId.longValue(), result.get(parentId.longValue()) + data.get("value").intValue());
                } else {
                    result.put(parentId.longValue(), data.get("value").intValue());
                }
            }
        }
        return success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "获得归属地分页")
    public CommonResult<VosNumberRespWithCountVO> getVosNumber(@Valid VosNumberPageReqVO pageReqVO) {
        PageResult<VosNumberDO> pageResult = vosNumberService.getVosNumberPage(pageReqVO);
        Map<Long, TenantDTO> tenantMap = tenantApi.getTenantMap(pageResult.getList().stream().map(VosNumberDO::getTenantId).collect(Collectors.toList()));

        VosNumberRespWithCountVO resp = new VosNumberRespWithCountVO();
        resp.setResult(VosNumberConverter.INSTANCE.convert0(pageResult, tenantMap));
        resp.setVosNumberCount(
                vosNumberService.getNumberCount(new VosNumberPageReqVO().setType(1).setLocationId(pageReqVO.getLocationId()))
        );
        resp.setRecallNumberCount(
                vosNumberService.getNumberCount(new VosNumberPageReqVO().setType(2).setLocationId(pageReqVO.getLocationId()))
        );
        resp.setUsedNumberCount(
                vosNumberService.getNumberCount(new VosNumberPageReqVO().setStatus(1).setLocationId(pageReqVO.getLocationId()))
        );
        resp.setIdleNumberCount(
                vosNumberService.getNumberCount(new VosNumberPageReqVO().setStatus(0).setLocationId(pageReqVO.getLocationId()))
        );

        return success(resp);
    }


}